/**
 *  user controller
 */
var path = require('path');
var formidable = require('formidable');
var fs = require('fs');

var User = require('../models/user.js');

var MESSAGES = {
    DATAMISS : '缺少必要数据！',
    REGISTSUCCESS: '注册成功！现在就登录~！',
    LOGINSUCCESS: '登录成功！',
    NOTLOGIN : '未登录，请登录后再操作！',
    SUCCESS  : '操作成功！',
    OLDPWDINCORRECT: '旧密码验证错误！',
    FAIL     : '操作失败！请稍后再试~',
    LOGINFAILED : '登录失败，用户名或密码错误！',
    LOGOUTSUCCESS: '退出成功！',
    LOGOUTED : '您长时间未操作，已经退出~',
    ILLEGALREQUEST: '非法请求'
};

exports.regist = function (req, res) {
    if(req.body.name && req.body.pwd && req.body.email){
        User.regist(req.body, function (user, e){
            if(e){
                res.json({code: 0, msg: e.toString()});
            }else{
                res.json({code: 1, msg: MESSAGES.REGISTSUCCESS});
            }
        });
    }else{
        res.json({code: 0, msg: MESSAGES.DATAMISS});
    }
};

exports.login = function (req, res, next) {

    if(req.body.email && req.body.pwd){

        User.login(req.body, function (obj, e){

            if(!obj){

                res.json({code: 0, msg: MESSAGES.LOGINFAILED});

            }else{
                //Ϊsession id 是用户名
                req.session.sid = obj.name;
                res.cookie('name', obj.name);
                res.cookie('userId', obj._id);
                res.json({code: 1, msg: MESSAGES.LOGINSUCCESS, user: obj});
            }
        });
    }else{

        res.json({code: 0, msg: MESSAGES.DATAMISS});

    }
};

exports.logout = function(req, res){
    //清除cookie
    res.clearCookie('name');
    res.clearCookie('connect.sid');
    if(!req.session.sid){
        res.json({code: 0, msg: MESSAGES.LOGOUTED});
    } else {
        //清除session
        req.session = null;
        res.json({code: 1, msg: MESSAGES.LOGOUTSUCCESS});
    }
};

exports.getUserInfo = function (req, res) {
    if(req.body.name == req.session.sid){
        User.findUserByName(req.body.name, function (e, user) {
            if(e){
                res.json({code: 0, msg: e});
            } else {
                res.json({code: 1, user: user});
            }
        });
    } else {
        res.json({code: 0, msg: MESSAGES.ILLEGALREQUEST});
    }
};

exports.updateAvatar = function (req, res) {
    var form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    form.uploadDir = path.join(__dirname, '../', '/public/imgs/avatars/');
    form.keepExtensions = true;
    form.maxFieldsSize = 204800;

    form.parse(req, function (err, fields, files) {
        if(err){
            res.json({code: 0, msg: err});
        } else {
            var fileType = files.file.type;
            var extName = '';

            if( fileType == 'image/pjpeg' || fileType == 'image/jpeg'){
                extName = 'jpg';
            } else if( fileType == 'image/png' || fileType == 'image/x-png' ){
                extName = 'png';
            } else if( fileType == 'image/gif'){
                extName = 'gif';
            }

            if(!extName){
                res.json({code: 0, msg: '只能上传图片~'});
                return ;
            }

            var fileName = fields.name + '.' + extName;
            var newPath = form.uploadDir + fileName;
            fs.renameSync(files.file.path, newPath);

            var savePath = 'imgs/avatars/' + fileName;
            User.updateAvatar(fields.name, savePath, function (e) {
                if(e){
                    res.json({code: 0, msg: MESSAGES.FAIL});
                } else {
                    res.json({code: 1, msg: MESSAGES.SUCCESS});
                }
            });
        }
    });
};

exports.updateEmail =  function (req, res) {
    if(req.body.name && req.body.email){
        User.updateEmail(req.body.name, req.body.email, function (e) {
            if(e){
                res.json({code: 0, msg: MESSAGES.FAIL});
            } else {
                res.json({code: 1, msg: MESSAGES.SUCCESS});
            }
        });
    } else {
        res.json({code: 0, msg: MESSAGES.DATAMISS});
    }
};
exports.updatePwd = function(req, res){
    var name = req.body.name;
    var oldPwd = req.body.oldPwd;
    var newPwd = req.body.newPwd;
    if(name && oldPwd && newPwd){
        User.findByNameAndPwd(name, oldPwd, function (e, user) {
            if(user){
                User.updatePwd(name,newPwd, function (e) {
                    if(e){
                        res.json({code: 0, msg: MESSAGES.FAIL});
                    } else {
                        //修改完密码后清除cookie和session重新登录
                        res.clearCookie('name');
                        res.clearCookie('connect.sid');
                        req.session = null;

                        res.json({code: 1, msg: MESSAGES.SUCCESS});
                    }
                });
            } else {
                res.json({code: 0, msg: MESSAGES.OLDPWDINCORRECT});
            }
        });
    } else {
        res.json({code: 0, msg: MESSAGES.DATAMISS});
    }
};

/**
 *
exports.updateName = function(req, res){
    if(req.body.name && req.body.newName){
        User.updateName(req.body.name, req.body.newName, function (error, numberAffected) {
            if(error){
                res.json({code: 0, msg: MESSAGES.updateFail});
            } else {
                res.json({code: 1, msg: MESSAGES.updateSuccess});
            }
        });
    } else {
        res.json({code: 0, msg: MESSAGES.dataMiss});
    }
};
 */

exports.searchUser = function (key, callback) {
    User.searchUser(key, function (err, users) {
        if(err){
            console.log(err);
            callback(null);
        } else {
            callback(users);
        }
    });
};

/**
 * 分页查询 需要以下几个参数
 * pageNumber: 第几页 开始是0
 * n : 每页个数
 */
exports.getUserByPage = function(req, res){
    var pageNumber = req.body.pageNumber;
    var n = req.body.n;
    if(pageNumber && n){
        User.getUserByPage(pageNumber*n, n, function (err, users) {
           if(err){
               console.log(err);
               res.json({code: 0, msg: '数据库查询错误！'});
           } else {
               User.getUsersCount(function(err, count){
                   if(err){
                       console.log(err);
                       res.json({code: 0, msg: '数据库查询错误！'});
                   } else {
                       res.json({code: 1, users: users, count: count});
                   }
               });
           }
        });
    } else {
        res.json({code: 0, msg: MESSAGES.DATAMISS});
    }
};

exports.findUserById = function(id, callback){
    User.findUserById(id, function(err, user){
        if(err){
            console.log(err);
            callback(null);
        } else {
            callback(user);
        }
    });
};

exports.deleteUserById = function(id, callback){
        User.deleteUserById(id, callback);
};